<script setup lang="ts">
import { computed, watch } from 'vue';
import { useForm } from '@sa/alova/client';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { createPermission, updatePermission } from '@/service/api/manage';
import { $t } from '@/locales';

defineOptions({
  name: 'ButtonOperateDrawer'
});
export type OperateType = NaiveUI.TableOperateType | 'add';

interface Props {
  /** the type of operation */
  operateType: OperateType;
  /** menu data */
  menuData: Api.Manage.Menu;
  /** edit row data */
  rowData?: Api.Manage.Permission | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<OperateType, string> = {
    add: '添加权限',
    edit: '编辑权限'
  };
  return titles[props.operateType];
});

type Model = Api.Manage.PermissionEdit;

// const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    id: 0,
    parentId: 0,
    type: 3,
    menuName: '',
    name: '',
    permissionKey: '',
    remark: '',
    status: 1,
    sortRank: 0
  };
}

const {
  loading: submitting,
  reset,
  send: submit,
  form: model,
  updateForm
} = useForm(formData => (props.operateType === 'add' ? createPermission(formData) : updatePermission(formData)), {
  initialForm: createDefaultModel(),
  resetAfterSubmitting: true
});

type RuleKey = Extract<keyof Model, 'name' | 'permissionKey' | 'status'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  name: defaultRequiredRule,
  permissionKey: defaultRequiredRule,
  status: defaultRequiredRule
};

const isEdit = computed(() => props.operateType === 'edit');

async function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if (props.operateType === 'add') {
    reset();

    const { id, name } = props.menuData;
    Object.assign(model.value, { parentId: id, menuName: name });
    return;
  }

  if (props.operateType === 'edit' && props.rowData) {
    updateForm(props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  await submit();
  window.$message?.success(isEdit.value ? $t('common.updateSuccess') : $t('common.addSuccess'));
  closeDrawer();

  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" :label-width="80">
        <NGrid>
          <NFormItemGi span="24" label="名称" path="name">
            <NInput v-model:value="model.name" placeholder="请输入名称" />
          </NFormItemGi>
          <NFormItemGi span="24" label="权限 Key" path="permissionKey">
            <NInput v-model:value="model.permissionKey" placeholder="请输入权限Key" />
          </NFormItemGi>
          <NFormItemGi span="24" label="备注" path="remark">
            <NInput v-model:value="model.remark" type="textarea" placeholder="请输入备注" />
          </NFormItemGi>
          <NFormItemGi span="24" label="状态" path="status">
            <PorDictRadio v-model:value="model.status" dict-code="common_status" value-to-number></PorDictRadio>
          </NFormItemGi>
          <NFormItemGi span="24" label="排序号" path="sortRank">
            <NInputNumber v-model:value="model.sortRank" placeholder="请输入排序号" />
          </NFormItemGi>
        </NGrid>
      </NForm>
      <template #footer>
        <NSpace :size="12" justify="end">
          <NButton quaternary @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" :loading="submitting" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>
